package com.th.switchnet;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

/**
 * apk安装后，第三方程序[即该程序]修改apk的配置文件 /res/raw目录下的文件，
 * 达到动态修改配置，而不需要重打包的目的
 * @author thduan
 * @date 2015-11-16
 */

public class MainActivity extends Activity implements OnClickListener{
	/** 提示语 */
	private TextView tipView;
	private EditText logView;
	private Button dev;
	private Button test;
	private Button online;
	
	private SwitchLogic switchLogic;
	
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        switchLogic = new SwitchLogic(this, new IEditNetListener() {
			
			@Override
			public void onSuccess() {
				endEdit(true, null);
			}

			@Override
			public void onStatusChange(String msg) {
				logView.setText(logView.getText().toString() + "\r\n" + msg);
			}

			@Override
			public void onFailed(String msg) {
				endEdit(false, msg);
			}
		});
        init();
    }
    
    private void init() {
    	tipView = (TextView) findViewById(R.id.tip);
    	logView = (EditText) findViewById(R.id.log);
    	dev = (Button) findViewById(R.id.dev);
    	test = (Button) findViewById(R.id.test);
    	online = (Button) findViewById(R.id.online);
    	
    	dev.setOnClickListener(this);
    	test.setOnClickListener(this);
    	online.setOnClickListener(this);
    }

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.dev:
			switchLogic.editNet(AppDefine.DEV_NET_VALUE);
			startEdit("开发环境");
			break;
		case R.id.test:
			switchLogic.editNet(AppDefine.TEST_NET_VALUE);
			startEdit("测试环境");
			break;
		case R.id.online:
			switchLogic.editNet(AppDefine.ONLINE_NET_VALUE);
			startEdit("现网环境");
			break;

		default:
			break;
		}
	}
	
	private void startEdit(String netType) {
		dev.setEnabled(false);
		test.setEnabled(false);
		online.setEnabled(false);
		tipView.setText("正在修改为：" + netType);
		logView.setText("");
	}
	
	private void endEdit(boolean isSuccess, String msg) {
		dev.setEnabled(true);
		test.setEnabled(true);
		online.setEnabled(true);
		if(isSuccess) {
			tipView.setText("修改成功");
		}else {
			tipView.setText("修改失败: " + msg);
		}
	}
}
